<?php

namespace App\Http\Controllers;

use App\Exceptions\CustomException;
use App\Http\Requests\Upload\UploadRequest;
use Illuminate\Http\Request;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class UploadController extends Controller
{
    public $config;

    public function __construct()
    {
        $this->config = config('sdk.qiniu');
    }

    public function upload(UploadRequest $request)
    {
        $inputs = $request->validated();
        $uploadMgr = new UploadManager();
        $auth = new Auth($this->config['ak'], $this->config['sk']);
        $token = $auth->uploadToken($this->config['bucket']);
        $key = md5($this->config['bucket'] . microtime()) . '.' . $inputs['file']->extension();
        list($ret, $error) = $uploadMgr->putFile($token, $key, $inputs['file']);
        if (!$error) {
            return successReturn('上传成功', [ 'path' => $ret['key'], 'src' => getUploadPath($ret['key'])]);
        }
        throw new CustomException(1004, '上传文件异常');
    }
}
